package product;

import models.BaseModel;
import org.apache.commons.lang.StringEscapeUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import util.common.UStringUtil;

import javax.persistence.*;
import java.util.List;
import java.util.Map;

/**
 * Created by liming on 16/7/12.
 */
@Entity
@Table(name = "product_spec_split")
public class ProductSpecSplit extends BaseModel{

    @ManyToOne
    @JoinColumn(name = "combo_product_spec_id")
    public ProductSpec comboProductSpec;

    @ManyToOne
    @JoinColumn(name = "split_product_spec_id")
    public ProductSpec splitProductSpec;

    @Column(name = "split_num")
    public Double splitNum = 0D;

    /**
     * 查询拆分产品明细列表
     */
    public static List<ProductSpecSplit> getSplitProductSpecList(long comboProSpecId){
        return ProductSpecSplit.find("comboProductSpec.id=?",comboProSpecId).fetch();
    }

    /**
     * 根据ID删除拆分明细
     */
    public static void delProSpecSplitById(Integer[] delIdArray){
        String delIdStr = UStringUtil.concatStr(",", delIdArray);
        ProductSpecSplit.delete("id in ("+delIdStr+")");

    }

    /**
     * 判断产品下是否有拆分明细
     */

    public static List checkIsSplit(List<Integer> ids){
        String checkIdStr = UStringUtil.concatStr(",", ids);
        String sqlData="select b.spec from product_spec_split a left join product_specs b on a.combo_product_spec_id = b.id where a.combo_product_spec_id in (%s) group by b.spec";
        Query query= Product.em().createNativeQuery(String.format(sqlData, StringEscapeUtils.escapeSql(checkIdStr)));
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String,Object>> resultList=query.getResultList();
        return resultList;
    }


}
